{% extends 'base.html' %}

{% block title %}执行详情 - API场景组合测试工具{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-3">
        <div class="col">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ url_for('index') }}">首页</a></li>
                    <li class="breadcrumb-item"><a href="{{ url_for('execution.list_executions') }}">执行记录</a></li>
                    <li class="breadcrumb-item active" aria-current="page">执行详情 #{{ execution.id }}</li>
                </ol>
            </nav>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col">
            <div class="card">
                <div class="card-header">
                    <h4><i class="fas fa-info-circle"></i> 执行信息</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <th style="width: 150px;">执行ID：</th>
                                    <td>{{ execution.id }}</td>
                                </tr>
                                <tr>
                                    <th>场景：</th>
                                    <td>
                                        <a href="{{ url_for('scene.get_scene', scene_id=execution.scene.id) }}">
                                            {{ execution.scene.name }}
                                        </a>
                                    </td>
                                </tr>
                                <tr>
                                    <th>环境：</th>
                                    <td>{{ execution.environment.name }}</td>
                                </tr>
                                <tr>
                                    <th>状态：</th>
                                    <td>
                                        <span class="badge {% if execution.status == 'SUCCESS' %}bg-success{% elif execution.status == 'RUNNING' %}bg-primary{% else %}bg-danger{% endif %}">
                                            {{ execution.status }}
                                        </span>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr>
                                    <th style="width: 150px;">开始时间：</th>
                                    <td>{{ execution.start_time }}</td>
                                </tr>
                                <tr>
                                    <th>结束时间：</th>
                                    <td>{{ execution.end_time or '-' }}</td>
                                </tr>
                                <tr>
                                    <th>耗时：</th>
                                    <td>
                                        {% if execution.start_time and execution.end_time %}
                                            {{ (execution.end_time - execution.start_time).total_seconds() }} 秒
                                        {% elif execution.status == 'RUNNING' %}
                                            正在运行中...
                                        {% else %}
                                            -
                                        {% endif %}
                                    </td>
                                </tr>
                                <tr>
                                    <th>模板数据ID：</th>
                                    <td>{{ execution.template_data_id or '-' }}</td>
                                </tr>
                            </table>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col">
                            <div class="d-flex justify-content-end">
                                {% if execution.status == 'RUNNING' %}
                                <button id="cancel-execution" class="btn btn-warning me-2" data-id="{{ execution.id }}">
                                    <i class="fas fa-stop"></i> 取消执行
                                </button>
                                {% endif %}
                                <button id="rerun-execution" class="btn btn-success me-2" data-id="{{ execution.id }}">
                                    <i class="fas fa-redo"></i> 重新执行
                                </button>
                                <a href="{{ url_for('execution.list_executions') }}" class="btn btn-secondary">
                                    <i class="fas fa-list"></i> 返回列表
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4><i class="fas fa-tasks"></i> 执行步骤</h4>
                    <div>
                        <button id="refresh-steps" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-sync"></i> 刷新
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th style="width: 50px;">#</th>
                                    <th>步骤名称</th>
                                    <th>类型</th>
                                    <th>状态</th>
                                    <th>开始时间</th>
                                    <th>结束时间</th>
                                    <th>耗时</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="step-list">
                                <tr>
                                    <td colspan="8" class="text-center">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col">
            <div class="card">
                <div class="card-header">
                    <h4><i class="fas fa-file-alt"></i> 执行结果</h4>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <div class="alert {% if execution.status == 'SUCCESS' %}alert-success{% elif execution.status == 'RUNNING' %}alert-info{% else %}alert-danger{% endif %}">
                            <strong>执行状态：</strong> {{ execution.status }}
                            {% if execution.status == 'FAILED' and execution.result %}
                                <br>
                                <strong>错误信息：</strong> {{ execution.result.error }}
                            {% endif %}
                        </div>
                    </div>
                    
                    {% if execution.result and execution.result is mapping %}
                    <div class="mb-3">
                        <h5>执行结果数据：</h5>
                        <pre class="bg-light p-3 rounded"><code>{{ execution.result|tojson(indent=2) }}</code></pre>
                    </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 步骤详情模态框 -->
<div class="modal fade" id="stepDetailModal" tabindex="-1" aria-labelledby="stepDetailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="stepDetailModalLabel">步骤详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="row mb-3">
                    <div class="col-md-6">
                        <table class="table table-borderless">
                            <tr>
                                <th style="width: 150px;">步骤名称：</th>
                                <td id="step-name"></td>
                            </tr>
                            <tr>
                                <th>步骤类型：</th>
                                <td id="step-type"></td>
                            </tr>
                            <tr>
                                <th>状态：</th>
                                <td id="step-status"></td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-6">
                        <table class="table table-borderless">
                            <tr>
                                <th style="width: 150px;">开始时间：</th>
                                <td id="step-start-time"></td>
                            </tr>
                            <tr>
                                <th>结束时间：</th>
                                <td id="step-end-time"></td>
                            </tr>
                            <tr>
                                <th>耗时：</th>
                                <td id="step-duration"></td>
                            </tr>
                        </table>
                    </div>
                </div>
                
                <ul class="nav nav-tabs" id="stepDetailTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="request-tab" data-bs-toggle="tab" data-bs-target="#request" type="button" role="tab" aria-controls="request" aria-selected="true">请求</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="response-tab" data-bs-toggle="tab" data-bs-target="#response" type="button" role="tab" aria-controls="response" aria-selected="false">响应</button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="script-tab" data-bs-toggle="tab" data-bs-target="#script" type="button" role="tab" aria-controls="script" aria-selected="false">脚本</button>
                    </li>
                </ul>
                <div class="tab-content p-3 border border-top-0 rounded-bottom" id="stepDetailTabsContent">
                    <div class="tab-pane fade show active" id="request" role="tabpanel" aria-labelledby="request-tab">
                        <div id="request-content">
                            <div class="mb-3">
                                <h6>请求URL：</h6>
                                <pre class="bg-light p-2 rounded"><code id="request-url"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>请求方法：</h6>
                                <pre class="bg-light p-2 rounded"><code id="request-method"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>请求头：</h6>
                                <pre class="bg-light p-2 rounded"><code id="request-headers"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>请求体：</h6>
                                <pre class="bg-light p-2 rounded"><code id="request-body"></code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="response" role="tabpanel" aria-labelledby="response-tab">
                        <div id="response-content">
                            <div class="mb-3">
                                <h6>状态码：</h6>
                                <pre class="bg-light p-2 rounded"><code id="response-status"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>响应头：</h6>
                                <pre class="bg-light p-2 rounded"><code id="response-headers"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>响应体：</h6>
                                <pre class="bg-light p-2 rounded"><code id="response-body"></code></pre>
                            </div>
                        </div>
                    </div>
                    <div class="tab-pane fade" id="script" role="tabpanel" aria-labelledby="script-tab">
                        <div id="script-content">
                            <div class="mb-3">
                                <h6>前置脚本：</h6>
                                <pre class="bg-light p-2 rounded"><code id="pre-script"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>后置脚本：</h6>
                                <pre class="bg-light p-2 rounded"><code id="post-script"></code></pre>
                            </div>
                            <div class="mb-3">
                                <h6>脚本执行结果：</h6>
                                <pre class="bg-light p-2 rounded"><code id="script-result"></code></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    // 预先定义模板变量
    const executionData = {
        id: "{{ execution.id }}",
        scene_id: "{{ execution.scene.id }}",
        environment_id: "{{ execution.environment.id }}",
        template_data_id: "{{ execution.template_data_id or '' }}",
        template_env_id: "{{ execution.template_env_id or '' }}"
    };
    
    $(document).ready(function() {
        const executionId = executionData.id;
        
        // 加载执行步骤
        function loadSteps() {
            $.get(`/execution/${executionId}/steps`, function(steps) {
                if (steps && steps.length > 0) {
                    const stepList = $('#step-list');
                    stepList.empty();
                    
                    steps.forEach(function(step, index) {
                        const statusClass = step.status === 'SUCCESS' ? 'bg-success' : 
                                          step.status === 'RUNNING' ? 'bg-primary' : 
                                          'bg-danger';
                        
                        const duration = step.end_time && step.start_time ? 
                            ((new Date(step.end_time) - new Date(step.start_time)) / 1000).toFixed(2) + ' 秒' : 
                            '-';
                        
                        stepList.append(`
                            <tr>
                                <td>${index + 1}</td>
                                <td>${step.name}</td>
                                <td>${step.type}</td>
                                <td><span class="badge ${statusClass}">${step.status}</span></td>
                                <td>${step.start_time || '-'}</td>
                                <td>${step.end_time || '-'}</td>
                                <td>${duration}</td>
                                <td>
                                    <button class="btn btn-sm btn-info view-step" data-step='${JSON.stringify(step)}'>
                                        <i class="fas fa-eye"></i> 查看
                                    </button>
                                </td>
                            </tr>
                        `);
                    });
                } else {
                    $('#step-list').html('<tr><td colspan="8" class="text-center">暂无步骤记录</td></tr>');
                }
            });
        }
        
        // 初始加载步骤
        loadSteps();
        
        // 刷新步骤
        $('#refresh-steps').click(function() {
            loadSteps();
        });
        
        // 如果执行状态为运行中，定时刷新
        if ('{{ execution.status }}' === 'RUNNING') {
            setInterval(function() {
                loadSteps();
                
                // 检查执行状态
                $.get(`/execution/${executionId}/status`, function(data) {
                    if (data.status !== 'RUNNING') {
                        location.reload(); // 如果状态已变更，刷新页面
                    }
                });
            }, 5000); // 每5秒刷新一次
        }
        
        // 查看步骤详情
        $(document).on('click', '.view-step', function() {
            const step = $(this).data('step');
            
            // 填充基本信息
            $('#step-name').text(step.name);
            $('#step-type').text(step.type);
            $('#step-status').html(`<span class="badge ${step.status === 'SUCCESS' ? 'bg-success' : step.status === 'RUNNING' ? 'bg-primary' : 'bg-danger'}">${step.status}</span>`);
            $('#step-start-time').text(step.start_time || '-');
            $('#step-end-time').text(step.end_time || '-');
            
            const duration = step.end_time && step.start_time ? 
                ((new Date(step.end_time) - new Date(step.start_time)) / 1000).toFixed(2) + ' 秒' : 
                '-';
            $('#step-duration').text(duration);
            
            // 填充请求信息
            if (step.request) {
                $('#request-url').text(step.request.url || '-');
                $('#request-method').text(step.request.method || '-');
                $('#request-headers').text(JSON.stringify(step.request.headers || {}, null, 2));
                $('#request-body').text(JSON.stringify(step.request.body || {}, null, 2));
            } else {
                $('#request-url, #request-method, #request-headers, #request-body').text('-');
            }
            
            // 填充响应信息
            if (step.response) {
                $('#response-status').text(step.response.status || '-');
                $('#response-headers').text(JSON.stringify(step.response.headers || {}, null, 2));
                $('#response-body').text(JSON.stringify(step.response.body || {}, null, 2));
            } else {
                $('#response-status, #response-headers, #response-body').text('-');
            }
            
            // 填充脚本信息
            if (step.script) {
                $('#pre-script').text(step.script.pre || '无前置脚本');
                $('#post-script').text(step.script.post || '无后置脚本');
                $('#script-result').text(JSON.stringify(step.script.result || {}, null, 2));
            } else {
                $('#pre-script, #post-script, #script-result').text('-');
            }
            
            // 显示模态框
            $('#stepDetailModal').modal('show');
        });
        
        // 取消执行
        $('#cancel-execution').click(function() {
            if (confirm('确定要取消此执行吗？')) {
                $.ajax({
                    url: `/execution/${executionId}/cancel`,
                    type: 'POST',
                    success: function(response) {
                        if (response.success) {
                            alert('执行已取消');
                            location.reload();
                        } else {
                            alert('取消失败: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('请求失败，请稍后重试');
                    }
                });
            }
        });
        
        // 重新执行
        $('#rerun-execution').click(function() {
            // 准备请求数据
            const requestData = {
                scene_id: executionData.scene_id,
                environment_id: executionData.environment_id,
                template_data_id: executionData.template_data_id || null,
                template_env_id: executionData.template_env_id || null
            };
            
            $.ajax({
                url: '/execution/',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(response) {
                    if (response.success) {
                        alert('场景执行已开始，执行ID: ' + response.execution_id);
                        // 跳转到执行详情页
                        window.location.href = '/execution/' + response.execution_id;
                    } else {
                        alert('执行失败: ' + response.message);
                    }
                },
                error: function() {
                    alert('请求失败，请稍后重试');
                }
            });
        });
    });
</script>
{% endblock %}